﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using UFPE.CIn.Abc.Primality.Util;

namespace UFPE.CIn.Abc.Primality.Algorithms
{
    public class TrialDivision : BaseAlgorithm
    {
        public override string AlgorithmName
        {
            get
            {
                return "Divisão por Tentativa";
            }
        }

        public override long Threshold
        {
            get
            {
                return 62356243511227;
            }
        }

        private static TrialDivision instance;

        public static TrialDivision Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new TrialDivision();
                }

                return instance;
            }
        }

        private BigInteger factor;

        /// <summary>
        /// Contains the smallest non-1 factor of the last running of the algorithm
        /// WARNING: If an even value is passed, Factor will return 1. Parse this behavior when using this property.
        /// </summary>
        public BigInteger Factor
        {
            get { return factor; }
        }

        public override bool Helper(BigInteger x)
        {
            factor = 1;
            
            BigInteger sqrtX = x.sqrt();

            for (BigInteger i = 3; i <= sqrtX; i+=2)
            {   
                if (x % i == 0)
                {
                    factor = i;

                    return false;
                }
            }

            return true;
        }
    }
}
